package com.wanggy.start;

import com.mysql.jdbc.Connection;
import com.wanggy.tool.MysqlUtils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ExportData {
    private static String url = "jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf8&useSSL=false";

    private static String username = "root";

    private static String password = "wgy0617";

    private static ResultSet resultSet = null;

    private static PreparedStatement preparedStatement;

    public static void main(String[] args) throws SQLException {
        String sql = "select * from users;";
        preparedStatement = MysqlUtils.getPreparedStatement(url, username, password, sql);
        String outPut = "E:\\output.csv";
        String context;
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(outPut));
            //表头信息
            writer.write("id,username,password,expire_time");
            writer.newLine();
            //获取查询结果
            resultSet = preparedStatement.executeQuery();
            //遍历查询结果
            while (resultSet.next()) {
                context = resultSet.getInt("id") + "," +
                        resultSet.getString("username") + "," +
                        resultSet.getString("password") + "," +
                        resultSet.getString("expire_time");
                writer.write(context);
                writer.newLine();
            }
            writer.close();

            System.out.println("文件生成成功！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }

        }
    }

}
